package org.dromara.authcode.util;

import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 百度地图工具类
 */
@Slf4j
@Component
public class BaiduMapUtil {

    @Value("${baidu.map.ak}")
    private String apiKey;

    private static final String GEOCODE_URL = "https://api.map.baidu.com/reverse_geocoding/v3";

    /**
     * 根据经纬度获取地址信息
     * @param longitude 经度
     * @param latitude 纬度
     * @return 地址信息
     */
    public String getAddress(double longitude, double latitude) {
        Map<String, String> params = new HashMap<>();
        params.put("ak", apiKey);
        params.put("output", "json");
        params.put("coordtype", "wgs84ll"); // 坐标类型
        params.put("location", latitude + "," + longitude); // 百度要求纬度在前

        try {
            String response = doGet(GEOCODE_URL, params);
            BaiduGeocodeResponse geocodeResponse = new Gson().fromJson(response, BaiduGeocodeResponse.class);
            if (geocodeResponse != null && geocodeResponse.getStatus() == 0) {
                BaiduGeocodeResponse.Result result = geocodeResponse.getResult();
                if (result != null) {
                    return result.getFormatted_address();
                }
            }
            log.warn("获取地址信息失败: {}", response);
        } catch (Exception e) {
            log.error("获取地址信息异常", e);
        }
        return null;
    }

    private String doGet(String url, Map<String, String> params) throws IOException {
        StringBuilder urlBuilder = new StringBuilder(url);
        if (params != null && !params.isEmpty()) {
            urlBuilder.append("?");
            for (Map.Entry<String, String> entry : params.entrySet()) {
                urlBuilder.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
            }
            urlBuilder.deleteCharAt(urlBuilder.length() - 1);
        }

        HttpGet httpGet = new HttpGet(urlBuilder.toString());
        try (CloseableHttpClient httpClient = HttpClients.createDefault();
             CloseableHttpResponse response = httpClient.execute(httpGet)) {
            HttpEntity entity = response.getEntity();
            return EntityUtils.toString(entity);
        }
    }

    // 百度地图响应数据结构
    @lombok.Data
    private static class BaiduGeocodeResponse {
        private int status;
        private Result result;

        @lombok.Data
        private static class Result {
            private String formatted_address;
            private String business;
            private AddressComponent addressComponent;

            @lombok.Data
            private static class AddressComponent {
                private String country;
                private String country_code;
                private String province;
                private String city;
                private String district;
                private String adcode;
                private String street;
                private String street_number;
                private String direction;
                private String distance;
            }
        }
    }
}
